<template>
  <div class="main">
    <div class="air-column">
      <h2>乘机人</h2>
      <el-form class="member-info" ref="from" :model="{ users }">
        <div
          class="member-info-item"
          v-for="(value, index) in users"
          :key="index"
        >
          <el-form-item
            label="乘机人类型"
            :prop="`users[${index}].username`"
            :rules="[
              {
                required: 'true',
                message: '请输入乘机人',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              placeholder="请输入姓名"
              v-model="value.username"
              class="input-with-select"
              @focus="handler(`users[${index}].username`)"
            >
            </el-input>
          </el-form-item>

          <el-form-item
            label="身份证号码"
            :prop="`users[${index}].id`"
            :rules="[
              {
                required: true,
                message: '请输入身份证号码',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              placeholder="请输入身份证密码"
              v-model="value.id"
              @focus="handler(`users[${index}].id`)"
              class="input-with-select"
            >
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers"
        >添加乘机人</el-button
      >
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <el-checkbox-group v-model="insurances">
        <div
          class="insurance-item"
          v-for="(value, index) in data.insurances"
          :key="index"
        >
          <el-checkbox :label="value.id" border>
            {{ value.type }}:￥{{ value.price }} / 份 x
            {{ users.length }} 最高赔付{{ value.compensation }}
          </el-checkbox>
        </div>
      </el-checkbox-group>
      <h2>发票</h2>
      <el-checkbox v-model="invoice">申请发票 </el-checkbox>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          :model="ruleForm"
          label-width="80px"
          ref="ruleForm"
          :rules="rules"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input
              v-model="ruleForm.contactName"
              @focus="submit('contactName')"
            ></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input
              placeholder="请输入内容"
              v-model="ruleForm.contactPhone"
              @focus="submit('contactPhone')"
            >
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input
              v-model="ruleForm.captcha"
              @focus="submit('captcha')"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          v-if="$store.state.userstore.userinfo.token"
          type="warning"
          class="submit"
          @click="handleSubmit"
          >提交订单</el-button
        >
      </div>
    </div>
    <!-- 登录 -->
    <el-form
      v-if="!$store.state.userstore.userinfo.token"
      :model="form"
      :rules="rules"
      ref="form"
      class="demo-ruleForm"
    >
      <el-form-item prop="username">
        <el-input
          v-model="form.username"
          placeholder="请输入用户"
          @focus="verification('username')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          @focus="verification('password')"
          type="password"
        ></el-input>
      </el-form-item>
      <p class="form-text">
        <nuxt-link to="#">忘记密码</nuxt-link>
      </p>
      <el-button type="primary" class="submit" @click="handlerLogin"
        >登录</el-button
      >
    </el-form>
  </div>
</template>

<script>
import { verification, airorders } from "@/utils/indexApi";
export default {
  props: ["data"],
  data() {
    return {
      // 乘机人应该是一个数组，里面的每一个对象都是一个乘机人 添加删除的话 只需要 push  / splice
      users: [
        {
          username: "小鲁班", // 乘机人姓名
          id: "199999283838939398", // 身份证号码
        },
      ],
      form: {
        username: "13800138000",
        password: "123456",
      },

      insurances: [], // 保险
      // contactName: "小鲁班", // 联系人姓名
      // contactPhone: "", //手机号
      // captcha: "000000", // 验证码
      invoice: false, // 发票
      ruleForm: {
        contactName: "小鲁班", // 联系人姓名
        contactPhone: "", //手机号
        captcha: "000000", // 验证码
      },

      // 表单验证
      rules: {
        contactName: [
          {
            required: "true",
            message: "请输入联系人",
            trigger: "blur",
          },
        ],
        contactPhone: [
          {
            required: "true",
            message: "请输入手机号码",
            trigger: "blur",
          },
        ],
        captcha: [
          {
            required: "true",
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    console.log(this.data);
    // 页面一进来就重新计算价格
    this.calcTotalPrice();
  },
  watch: {
    // 需要监听价格的变化和保险的变化
    users() {
      this.calcTotalPrice();
    },
    insurances() {
      this.calcTotalPrice();
    },
  },
  methods: {
    // 用户输入不正确时重新获取焦点验证信息就重新验证
    verification(prop) {
      this.$refs.form.clearValidate(prop);
    },
    // 登录
    handlerLogin() {
      this.$store.dispatch("userstore/login", this.form);
      this.$message.success("登录成功");
    },
    // 表单验证
    handler(prop) {
      this.$refs.from.clearValidate(prop);
    },
    submit(prop) {
      this.$refs.ruleForm.clearValidate(prop);
    },
    calcTotalPrice() {
      // 计算机票价格
      let res = 0;
      res += this.data.seat_infos.par_price * this.users.length;
      // 计算保险价格
      // 当前被选中的保险是 this.insurances 需要根据遍历能够拿到选中的id
      this.insurances.forEach((item) => {
        // 这里拿到了id 需要到原来的保险数据中查找出对应的价格
        // 在遍历当前的保险价格
        this.data.insurances.forEach((element) => {
          // 如果当前id 等于被选中的保险 就计算价格
          if (element.id == item) {
            res += element.price * this.users.length;
          }
        });
      });
      // 计算出价格就传给父组件
      this.$emit("totalPrice", res);
      console.log(res);
    },
    // 添加乘机人
    handleAddUsers() {
      // 点击添加的时候就push 一个对象就是每一个乘机人的信息
      this.users.push({
        username: "",
        id: "",
      });
    },

    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },

    // 发送手机验证码
    async handleSendCaptcha() {
      // 发送请求验证码
      if (this.ruleForm.contactPhone.length != "") {
        const res = await verification({ tel: this.ruleForm.contactPhone });
        const { code } = res.data;
        if (code) {
          this.$message.success(`验证码为${code}`);
        }
      } else {
        this.$message.error("请输入手机号码");
      }
    },

    // 提交订单
    handleSubmit() {
      this.$refs.ruleForm.validate((callback) => {
        if (callback) {
          const data = {
            users: this.users,
            insurances: this.insurances,
            contactName: this.ruleForm.contactName,
            contactPhone: this.ruleForm.contactPhone,
            invoice: this.invoice,
            seat_xid: this.$route.query.seat_xid,
            air: this.$route.query.id,
            captcha: this.ruleForm.captcha,
          };
          this.$axios({
            url: "/airorders",
            method: "post",
            data,
            headers: {
              Authorization:
                "Bearer " + this.$store.state.userstore.userinfo.token,
            },
          }).then((res) => {
            let { data, message } = res.data;
            console.log(data);
            if (message === "订单提交成功") {
              this.$message.success("订单提交成功");
              this.$router.push({ path: "/air/pay?id=" + data.id });
            }
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 8px;
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.demo-ruleForm {
  width: 400px;

  .submit {
    margin: 50px auto;
    display: block;
    width: 250px;
    height: 50px;
  }

  .form {
    padding: 25px;
  }

  .form-item {
    margin-bottom: 20px;
  }

  .form-text {
    font-size: 12px;
    color: #409eff;
    text-align: right;
    line-height: 1;
  }

  .submit {
    width: 100%;
    margin-top: 10px;
  }
}
</style>